package com.example.download.fragment

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.download.Help
import com.example.download.R
import com.example.download.ViewModel.BViewModel
import com.example.download.adapter.downloading_itemAdapter


class BFragment : Fragment() {

    private lateinit var iv_dli_add: ImageView
    private lateinit var iv_fb_dli_frame: ImageView
    private lateinit var tv_fb_dli_nt: TextView
    private lateinit var downloadingView: RecyclerView
    private lateinit var downloadingItemAdapter: downloading_itemAdapter
    private lateinit var cl_fb_button : ConstraintLayout
    private lateinit var bViewModel: BViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_b, container, false)
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        bViewModel = ViewModelProvider(this).get(BViewModel::class.java)
        downloadingView = view.findViewById(R.id.fb_recyclerViewB)
        downloadingView.layoutManager = LinearLayoutManager(requireContext())
        downloadingItemAdapter = downloading_itemAdapter(mutableListOf())
        downloadingView.adapter = downloadingItemAdapter


        iv_fb_dli_frame = view.findViewById(R.id.iv_fb_dli_frame)
        tv_fb_dli_nt = view.findViewById(R.id.tv_fb_dli_nt)

        bViewModel.downloadingItemList.observe(viewLifecycleOwner, Observer { itemList ->
            downloadingItemAdapter.updateData(itemList)
            if(itemList.isNotEmpty()){
                iv_fb_dli_frame.visibility = View.GONE
                tv_fb_dli_nt.visibility = View.GONE
            }else{
                iv_fb_dli_frame.visibility = View.VISIBLE
                tv_fb_dli_nt.visibility = View.VISIBLE
            }
        })


        iv_dli_add = view.findViewById(R.id.iv_dli_add)
        iv_dli_add.setOnClickListener {
            bViewModel.addNewItem()
        }
        cl_fb_button = view.findViewById(R.id.cl_fb_button)
        cl_fb_button.setOnClickListener {
            val intent = Intent(requireContext(), Help::class.java)
            startActivity(intent)
        }
    }
}